#!/usr/bin/env python

print "Content-Type: text/html\n\n";

import MySQLdb
import htmlUtils
import dbUtils
import cgi;

# this gets around a nasty bug which
# assumes os.environ['USER'] will be set
import os
os.environ['USER'] = "apache"

#import semantic;
import logic
import db_info

db = MySQLdb.connect(host=db_info.DB_HOST, user=db_info.DB_USERNAME, passwd=db_info.DB_PASSWORD, db=db_info.DB_DATABASE)


#  - Matthew Fay and Jodyann Coley
#  - Eric Lieberman and Mike Lin
print """
<html>
<head>
  <title>SemanticSQL</title>
  <link rel="StyleSheet" href="style.css">

  <script>
    function focusText() {
      var tbox = document.getElementById("input_textbox");
      tbox.focus();
    }
  </script>
</head>

<body onLoad="focusText()">
<font size=6><b>LogicSemantic</b></font><br>
<font size=4>Natural Language Conversion: English to Logic<br>
<a href="index.py">Home</a> ---
<a href="dictionary.py">Dictionary</a> ---
<a href="report/">Report</a><br>
<p>

Please type in a sentence:<br>
<form action="index.py" method="GET">
  <input type="hidden" name="action" value="input">
  <input type="textbox" size=60 id="input_textbox" name="input">
  <input type="submit" value="Submit">
</form>
<p>
"""

form = cgi.FieldStorage()
action = "none";
if (form.has_key("action")):
    action = form["action"].value;

if action == "none":
    "" # do nothing
elif action == "clear":
    dbUtils.clearTable(db, "fol");
    htmlUtils.writeStatusMessage("Cleared the database");    
elif action == "input":
    sentence = form["input"].value;
    htmlUtils.writeStatusMessage("Last Sentence: " + sentence);
    print '<pre>';
    try:
        result = logic.process_sentence(sentence, db)
        print result
    except Exception as e:
        print e.strerror()
    print '</pre>';
else:
    htmlUtils.writeStatusMessage("Unknown command: " + action);
print """
<p>
<font size=5><b>Database Status:</b></font>

<table border=0><tr><td>
<form action="index.py" method="GET">
  <input type="hidden" name="action" value="clear">
  <input type="submit" value="Clear Scene">
</form>

</td><td>

</td></tr></table>

<p>
"""

print '<table border=0 cellpadding=5>';
print '<tr><td valign=top>';

print 'Facts:<br>';
htmlUtils.writeTable(db, "fol");
print '</td><td valign=top>';

print '</td></tr></table>';

print '</body>';

print '</html>';
print "\n";



